const jsonParse = require('../../lib/jsonParse')
const SysDict = require('../../schemas/dict').SysDictList
const SysDictValueList = require('../../schemas/dict').SysDictValueList


const {
    ObjectId
} = require('mongodb')

module.exports = {
    /**
     * 获取参数列表
     */
    async getDictList(req, res) {
        let total = await SysDict.count()
        let {
            pageSize,
            pageNum,
            dictTypeName
        } = req.body;
        let data = {}
        if (dictTypeName) {
            data.dictTypeName = dictTypeName
        }
        SysDict.find(data).skip(pageSize * (pageNum - 1)).limit(pageSize).then(dict => {
            jsonParse.sendResult(res, 200, {
                total,
                records: dict
            }, '查询成功')
        })
    },

    /**
     * 保存参数
     */
    saveDict(req, res) {
        // const {dictName, dictType, remark, status} = req.body
        const newDict = new SysDict({
            ...req.body,
        })
        newDict.save().then(dict => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * 更新参数
     */
    updateDict(req, res) {
        SysDict.findByIdAndUpdate({
            _id: new ObjectId(req.body._id)
        }, {
            $set: {
                ...req.body
            }
        }).then(dict => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * 删除参数
     */
    deleteDict(req, res) {
        SysDict.findByIdAndDelete({
            _id: new ObjectId(req.query.id)
        }).then(dict => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * 获取参数值列表
     */
    getDictValueList(req, res) {
        let data = {
            dictType: req.body.dictType
        }
        if (req.body.dictName) {
            data.dictName = req.body.dictName
        }
        SysDictValueList.find(data).then(dict => {
            jsonParse.sendResult(res, 200, dict, '查询成功')
        })
    },

    /**
     * 保存参数值
     */
    saveDictValue(req, res) {
        const newDictValue = new SysDictValueList({
            ...req.body,
            createTime: new Date().getTime(),
            createBy: 123
        })
        newDictValue.save({
            ...req.body
        }).then(dict => {
            jsonParse.sendResult(res, 200)
        })
    },

    /**
     * 更新参数值
     */
    updateDictValue(req, res) {
        SysDictValueList.findByIdAndUpdate({
            _id: new ObjectId(req.body._id)
        }, {
            $set: {
                ...req.body
            }
        }).then(dict => {
            jsonParse.sendResult(res, 200)
        })
    }
}